package com.tiger.admin.http.logs;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tiger.admin.Db;
import com.tiger.admin.SaveOperateLog;
import com.tiger.admin.http.common.member.MemberService;
import com.tiger.admin.http.logs.dto.ExportDto;
import com.tiger.admin.http.logs.dto.PageDto;
import com.tiger.db.entity.ExportTask;
import com.tiger.db.entity.Student;
import com.tiger.mongodb.entity.PortalLoginLog;
import com.tiger.utils.Md5;
import com.tiger.utils.ResponseUtil;
import jakarta.servlet.http.HttpSession;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDate;
import java.util.HashMap;

@RestController
@RequestMapping("portalLoginLog")
public class PortalLoginLogController {
    @Value("${Upload.dist}")
    private String dist;

    private final MemberService memberService;

    private final Db db;

    private final PortalLoginLogService portalLoginLogService;

    public PortalLoginLogController(MemberService memberService, Db db, PortalLoginLogService portalLoginLogService) {
        this.memberService = memberService;
        this.db = db;
        this.portalLoginLogService = portalLoginLogService;
    }

    @PostMapping("page")
    public Object page(@RequestBody PageDto page, @RequestAttribute("memberId") long memberId) {
        return ResponseUtil.successRes(portalLoginLogService.page(page));
    }

    @SaveOperateLog("导出门户登录日志")
    @PostMapping("export")
    public Object export(@RequestBody ExportDto dto, @RequestAttribute("memberId") long memberId) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("登录日志");
        Row row = sheet.createRow(0);

        Cell cell0 = row.createCell(0);
        cell0.setCellValue("日期时间");

        Cell cell1 = row.createCell(1);
        cell1.setCellValue("账号");

        Cell cell2 = row.createCell(2);
        cell2.setCellValue("ip");

        Cell cell3 = row.createCell(3);
        cell3.setCellValue("浏览器");

        Cell cell4 = row.createCell(4);
        cell4.setCellValue("位置");

        Cell cell5 = row.createCell(5);
        cell5.setCellValue("登录方式");


        Instant now = Instant.now();
        long time = now.getEpochSecond();

        LocalDate today = LocalDate.now();
        // 获取当前年份
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();


        String monthStr = String.valueOf(month);
        String dayStr = String.valueOf(day);
        if(month < 10) {
            monthStr = "0" + monthStr;
        }
        if(day < 10) {
            dayStr = "0" + dayStr;
        }

        Md5.generate(memberId + "_" + time);

        //2024/03/10
        String subDir = String.valueOf(Paths.get(String.valueOf(year), monthStr, dayStr));
        File dir = new File(String.valueOf(Paths.get(dist, subDir)));
        dir.mkdirs();


        String fileName = String.valueOf(Paths.get(subDir, Md5.generate(memberId + "_" + time) + ".xlsx"));
        String filePath = String.valueOf(Paths.get(dist, fileName));

        try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
            workbook.write(outputStream);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 关闭工作簿以释放内存资源
        workbook.close();



        ExportTask task = new ExportTask();
        task.setCreatorId(memberId);
        task.setStatus(0);
        task.setUrl(fileName);
        task.setType(2);
        task.setCreateTime(time);


//        long[] dateRange = new long[2];
//
//        if(dto.getStartTime() > 0) {
//            dateRange[0] = dto.getStartTime();
//        }
//        if(dto.getEndTime() > 0) {
//            dateRange[1] = dto.getEndTime();
//        }
//
//        if(dateRange[0] > 0 || dateRange[1] > 0) {
//            task.setDateRange(dateRange);
//        }else  {
//            task.setDateRange(null);
//        }


        boolean r = db.exportTask.save(task);
        if(r) {
            portalLoginLogService.export(task.getId(), dto, filePath);
            return ResponseUtil.successRes();
        }else {
            return ResponseUtil.failRes();
        }
    }

    /**
     * 查看敏感信息
     * */
    @PostMapping("secrecy/{id}")
    public Object secrecy(@RequestBody() HashMap<String, String> data, @PathVariable("id") String id, HttpSession session) {
        String password = data.get("password");
        if(password == null || password.isEmpty()) return ResponseUtil.failRes();


        if(session.getAttribute(password) == null) return ResponseUtil.failRes("密码错误");

        PortalLoginLog log = portalLoginLogService.query(id);

        return ResponseUtil.successRes(log);
    }
}
